package com.flying.client.network.msg;

import org.jboss.netty.buffer.ChannelBuffer;

import com.flying.client.network.IMsgSink;

public class OWMsg {
	
	public static final int TIMEOUT_MILLS = 1000 * 15; //15秒
	/**
	 * 消息包头部长度
	 * [MsgId(short)|MsgType(short)|Len(int)]
	 */
	public static final int MSG_HEADER_LEN = 8;
	/**
	 * 消息序列号(客户端消息标识)
	 */
	protected short msgSeq;
	/**
	 * 消息类型
	 */
	protected short msgType;
	/**
	 * 消息体buffer
	 */
	private ChannelBuffer bodyBuffer;
	/**
	 * 消息回调
	 */
	protected IMsgSink msgSink = null;
	/**
	 * 是否反馈消息
	 */
	protected boolean needFeedback = false;
	/**
	 * 发送时间
	 */
	protected long sendTime = 0;
	/**
	 * 可用锁
	 */
	private Object enableLocker = new Object();
	/**
	 * 可用状态
	 */
	protected boolean enable = true;
	
	public OWMsg (short msgType)
	{
		this(msgType,null);
	}
	
	public OWMsg(short msgType,ChannelBuffer buffer)
	{
		this.msgType = msgType;
		this.bodyBuffer = buffer;
	}
	/**
	 * 设置序列号
	 * @param msgSeq
	 */
	public void setMsgSeq(short msgSeq)
	{
		this.msgSeq = msgSeq;
	}
	/**
	 * 获取序列号
	 * @return
	 */
	public short getMsgSeq()
	{
		return msgSeq;
	}
	/**
	 * 获取消息类型
	 * @return
	 */
	public short getMsgType()
	{
		return msgType;
	}
	/**
	 * 获取是否反馈
	 * @return
	 */
	public boolean isNeedFeedback()
	{
		return needFeedback;
	}
	/**
	 * 获取时间
	 * @return
	 */
	public long getSendTime()
	{
		return sendTime;
	}
	/**
	 * 是否超时
	 * @param curTimeMills
	 * @return
	 */
	public boolean isTimeout(long curTimeMills)
	{
		return curTimeMills > sendTime + TIMEOUT_MILLS;
	}
	/**
	 * 设置时间
	 */
	public void setSendTime(long mills)
	{
		sendTime = mills;
	}
	/**
	 * 获取消息体缓存
	 * @return
	 */
	public ChannelBuffer getBodyBuffer()
	{
		return bodyBuffer;
	}
	/**
	 * 获取是否可用状态
	 * @return
	 */
	public boolean isEnable()
	{
		synchronized(enableLocker)
		{
			return enable;
		}
	}
	/**
	 * 设置为不可用状态
	 */
	public void disable()
	{
		synchronized(enableLocker)
		{
			enable = false;
		}
	}
	/**
	 * 设置为可用
	 */
	public void enable()
	{
		synchronized(enableLocker)
		{
			enable = true;
		}
	}
	/**
	 * 错误事件
	 */
	public void onError()
	{
		if (msgSink != null)
		{
			msgSink.onError();
		}
	}
	/**
	 * 超时事件
	 */
	public void onTimeout()
	{
		if (msgSink != null)
		{
			msgSink.onTimeout();
		}
	}
	/**
	 * 发送成功事件
	 */
	public void onSended()
	{
		if (msgSink != null)
		{
			msgSink.onSended();
		}
	}
}
